package cn.weiwh.mailsend.mail.service;

import cn.weiwh.mailsend.mail.manager.SendMail;
import cn.weiwh.mailsend.mail.util.ConfigReadInit;
import cn.weiwh.mailsend.mail.util.FilereadUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
@Component
public class SendMailService {
    private static final Logger logger= LoggerFactory.getLogger(SendMailService.class);
    @Autowired
    private SendMail sendMail;
    public void sendEmail(){
        File f=new File(ConfigReadInit.fileFrom);
        String msg=ConfigReadInit.content;
        if(f.exists()){
            logger.info("wwh-------文件存在"+f.getPath()+"\t开始执行发送。。。");
            //首先获取到发送的内容和附件
            boolean isOk=sendMail.sendTextEmail( getMessage(f,msg),f);
            if(isOk){
                f.delete();
                logger.info("wwh---文件已删除。");
            }
        }else{
            logger.info("wwh-------文件不存在"+f.getPath()+"\t不能发送！");
        }
    }

    /**
     * 根据获取的文件值，插入将要发送的内容里去
     * @param f 获取文件
     * @param msg 未替换的邮件内容
     * @return
     */
    public static String getMessage(File f,String msg) {
        logger.info("wwh---开始读取文件内容准备替换。。。");
        int index;
        StringBuilder sb=new StringBuilder(msg);
        String[] str=FilereadUtil.getStrByFile(f).split(",");

            for (String s:str) {
                index=sb.indexOf("_");
                sb.replace(index,index+1,s);
            }

        return sb.toString();
    }


}
